package com.leet.code.lcof;

import com.algorithm.model.TreeNode;
import com.algorithm.model.TreeNodeService;

public class Code55_2 {
    public static void main(String[] args) {

        TreeNode treeNode = TreeNodeService.getTree();
        System.out.println(new Code55_2().isBalanced(treeNode));

    }

    public boolean isBalanced(TreeNode root) {
        return dfs(root, 0) != -1;
    }


    public int dfs(TreeNode treeNode, int i) {
        if (treeNode == null) {
            return i;
        }
        int l = dfs(treeNode.left, i + 1);
        int r = dfs(treeNode.right, i + 1);
        if (l == -1 || r == -1 || l - r <= -2 || l - r >= 2) {
            return -1;
        }
        return Math.max(l, r);
    }


}
